import { createApp } from 'vue';
import './app.scss';
import './utils/extends';
import api from '@/api';
import { cache, unShort } from '@/utils';
import Taro from '@tarojs/taro';
import { isLogin, loginDelegate } from './hooks';
import { APPID, initExt, sysConfig } from './utils/config';


const App = createApp({
  onLaunch(options) {
    initExt()
    api.sys.config().then(config => {
      sysConfig.value = config;
    });
    if (options.query?.scene) {
      options.query.scene = options.query.scene.split('_')[0];
      options.query.uid = unShort(options.query.scene);
    }
    if (options.query?.uid) {
      cache.set('InviteId', options.query.uid);
    }
    if (!isLogin()) {
      Taro.login({
        async success(r) {
          const token = await api.user.userLoginByPlatform({
            jsCode: r.code,
            appId: APPID.value
          });
          cache.set('token', token, 3600 * 24 * 7 - 20);
          for (let i = 0; i < loginDelegate.length; i++) {
            try {
              loginDelegate[i].call(null);
            } catch (error) {
              console.error(error);
            }
          }
          if (options.query?.uid) {
            api.user.userBindInvite(options.query.uid);
          }
          loginSuccessAfter();
        }
      });
    } else {
      if (options.query?.uid) {
        api.user.userBindInvite(options.query.uid);
      }
      loginSuccessAfter();
    }
    Taro.useError(err => {
      console.log(err);
    });
  },
  onShow(options) {},
  onPageNotFound(options) {}
  // 入口组件不需要实现 render 方法，即使实现了也会被 taro 所覆盖
});

const loginSuccessAfter = () => {};

export default App;
